<template>
  <div>
    <el-card class="search-card" v-loading="searchFormLoading">
      <BasicTableForm
        v-if="showSearchForm"
        ref="formData"
        isScalingBtn
        :colNumOfRow="4"
        :formItemWidth="'120px'"
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
        :handleClearForm="handleClearForm"
      />
    </el-card>
    <el-card class="table-card">
      <basic-table
        showSelectCol
        showPagination
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :total="pagination.totalNum"
        :selectionChange="selectionChange"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <el-row type="flex" justify="space-between" align="middle" slot="content_context">
          <el-row>
            <el-button
              v-for="(item, index) in renderBtns()"
              size="mini"
              type="primary"
              :key="index"
              :loading="item.loading"
              :disabled="item.disabled"
              @click="item.method"
            >{{ item.btnTxet }}</el-button>
          </el-row>
          <el-row><span>本页库存金额合计:{{totalAmount || 0}}</span></el-row>
        </el-row>
      </basic-table>
    </el-card>
    <deal-dialog
      :selectList="tableInfo.selection"
      :processingModeOptions="searchOptionObj.processingType"
      :dialogVisible="dealDialogVisible"
      @hide-handler="handleCloseDialog"
      @handle-confirm="handleDealConfirm"
    ></deal-dialog>
    <log-dialog
      :dialogVisible="logDialogVisible"
      :dialogData="dealLogList"
      @hide-handler="handleCloseDialog"
    ></log-dialog>
    <!-- 跨区域转派 -->
    <TransferDialog :transferVisible.sync="transferVisible" :areaOptions="searchOptionObj.area" @handleTransfer="handleTransfer"/>
    <!-- 出入库记录 -->
    <RecordDialog :recordVisible.sync="recordVisible" :selectIds="selectIds" />
    <!-- 区域数据 -->
    <AreaData :areaDataVisible.sync="areaDataVisible" :selectIds="selectIds" />
    <!-- 产生原因 -->
    <SelectCauseReason :caseReasonVisible.sync="caseReasonVisible" :selectIds="selectIds"  @getTableData="getTableDataAction"/>
    <!-- 复核 -->
    <ReviewDialog :reviewVisible.sync="reviewVisible" :selectIds="selectIds"  @getTableData="getTableDataAction"/>
    <!-- 备注设置 -->
    <SetRemarkDialog :remarkVisible.sync="remarkVisible" />
    <!-- 查看供应商 -->
    <SpplierDialog :spplierVisible.sync="spplierVisible" :itemId="itemId"/>
    <!-- 批量维护 -->
    <BatchUpload :exportVisible.sync="exportVisible" />
  </div>
</template>
<script>
import {
  queryStockListService,
  querySearchConditionOptionsService,
  exportStockFileService,
  dealLogService,
  transferGoodsService,
  submitStockService,
  validProcessAuthService,
  resetProcessDeptService
} from '@api/stock/stockOverflow';
import BasicTableForm from '../../components/BasicForm';
import BasicTable from '@/components/skusTable';
import DealDialog from './components/DealStockDialog';
import LogDialog from './components/DealLogDialog';
import TransferDialog from './components/TransferDialog';
import RecordDialog from './components/RecordDialog';
import AreaData from './components/AreaData';
import SelectCauseReason from './components/SelectCauseReason';
import ReviewDialog from './components/ReviewDialog';
import SetRemarkDialog from './components/SetRemarkDialog';
import SpplierDialog from './components/SpplierDialog';
import BatchUpload from './components/BatchUpload';
import { initFormItemList, initTableColumns } from './constants';
import { createExcelByExport, toFixedCustomize, setAuthBtnId } from '@/utils/bizUtils';
import { mapGetters } from 'vuex';

export default {
  components: {
    BasicTableForm,
    BasicTable,
    DealDialog,
    LogDialog,
    TransferDialog,
    RecordDialog,
    AreaData,
    SelectCauseReason,
    ReviewDialog,
    SetRemarkDialog,
    SpplierDialog,
    BatchUpload
  },
  data () {
    return {
      exportVisible: false,
      spplierVisible: false,
      remarkVisible: false,
      reviewVisible: false,
      caseReasonVisible: false,
      areaDataVisible: false,
      recordVisible: false,
      transferVisible: false,
      dealDialogVisible: false,
      logDialogVisible: false,
      showSearchForm: false,
      exportLoading: false,
      searchFormLoading: false,
      transferLoading: false,
      resetLoading: false,
      submitLoading: false,
      formItemList: [],
      formData: {
        processingStatusList: ['0', '1', '3', '4'], // 处理状态
        categoryUuids: null, // 品类
        isLogistic: null, // 是否物流中心
        companyId: null, // 分公司
        areaId: null, // 区域
        centerId: null, // 归属中心
        stockAttr: null, // 存量溢出属性
        processingUserName: '', // 处理人
        brandUuid: null, // 品牌
        departmentId: null, // 归属部门
        productName: '', // 商品名称
        skuNo: '', // 商品编码
        processingType: null, // 处理方式
        planDigestionRegion: null, // 预计消化区间
        isSolveDateModify: null, // 预计解决日期是否变化
        statisticsDate: [], // 统计日期
        planSolveUpdateDate: [], // 预计解决日期
        enumTempProduct: '', // 商品类型
        stockId: null, // 仓位
        supplyName: '', // 供应商
        isSeason: null, // 是否季节性商品
        qualityGuaranteePeriodType: null, // 保质期类型
        productStockAttribute: null, // 存量属性
        isSolutionReasonable: null, // 是否合理
        stockDate: [], // 新做库存日期
        unStockDate: [], // 不做库存日期
        processDepartmentId: '', // 处理部门
      },
      tableInfo: {
        list: [],
        columns: [],
        loading: false,
        selection: []
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 100
      },
      pageSizes: [100, 500, 1000],
      // 查询条件下拉集合
      searchOptionObj: {
        processingStatus: [], // 处理状态
        processingType: [], // 处理方式
        planDigestionRegion: [], // 预计消化区间
        processingStatusList: [], // 处理状态
        isLogistic: [], // 是否物流中心
        area: [], // 区域
        stockAttr: [], // 存量溢出属性
        isSolveDateModify: [], // 预计解决日期是否变化
        enumTempProducList: [], // 商品类型集合
        qualityGuaranteePeriodType: [], // 保质期类型
        productStockAttribute: [], // 存量属性
        centerList: [], // 归属中心
      },
      // 处理日志列表
      dealLogList: [],
      // 库存金额合计
      totalAmount: 0,
      itemId: null
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    notSelected () {
      return this.tableInfo.selection.length === 0
    },
    selectIds () {
      return this.tableInfo.selection.map(item => item.id)
    }
  },
  created () {
    this.tableInfo.columns = initTableColumns(this);
    this.getSearchConditionOptionsAction();
    const { planSolveDateBegin = '', planSolveDateEnd = '', processingStatus, reviewTimeStart, reviewTimeEnd, isPushManage, processingType, processDepartmentId, isSolutionReasonable } = this.$route.query;
    if (processingStatus) {
      console.log(processingStatus)
      this.formData.processingStatusList = Array.isArray(processingStatus) ? processingStatus : processingStatus.split(',');
      this.formData.planSolveUpdateDate = [planSolveDateBegin, planSolveDateEnd];
      this.formData.reviewTimeStart = reviewTimeStart;
      this.formData.reviewTimeEnd = reviewTimeEnd;
      this.formData.isPushManage = isPushManage;
      this.formData.processingType = processingType;
      this.formData.processDepartmentId = processDepartmentId;
      this.formData.isSolutionReasonable = isSolutionReasonable;
      this.getTableDataAction()
    }
  },
  methods: {
    renderBtns () {
      const btns = [
        { btnTxet: '导出', loading: this.exportLoading, disabled: this.pagination.totalNum == 0, method: this.handleExportFile, hasAuth: true },
        { btnTxet: '导入', method: () => { this.handleOpenDialog('exportVisible') }, hasAuth: true },
        { btnTxet: '处理', disabled: this.notSelected, method: this.handleDealStock, hasAuth: true },
        { btnTxet: '出入库记录', disabled: this.notSelected, method: () => { this.handleOpenDialog('recordVisible') }, hasAuth: true },
        { btnTxet: '转集团', loading: this.transferLoading, disabled: this.notSelected, method: () => { this.handleTransfer(1) }, hasAuth: true },
        { btnTxet: '转区域', loading: this.transferLoading, disabled: this.notSelected, method: () => { this.handleTransfer(2) }, hasAuth: true },
        { btnTxet: '跨区域转派', loading: this.transferLoading, disabled: this.notSelected, method: () => { this.handleCrossRegionalTransfer(3) }, hasAuth: true },
        { btnTxet: '产生原因', disabled: this.notSelected, method: () => { this.handleOpenDialog('caseReasonVisible') }, hasAuth: true },
        { btnTxet: '区域数据', disabled: this.notSelected, method: () => { this.handleOpenDialog('areaDataVisible') }, hasAuth: true },
        { btnTxet: '备注设置', disabled: this.notSelected, method: () => { this.handleOpenDialog('remarkVisible') }, hasAuth: true },
        { btnTxet: '复核', disabled: this.notSelected, method: () => { this.handleOpenDialog('reviewVisible') }, hasAuth: true },
        { btnTxet: '重置处理部门', loading: this.resetLoading, disabled: this.notSelected, method: this.handleResetDepartment, hasAuth: true },
        { btnTxet: '提交', loading: this.submitLoading, disabled: this.notSelected, method: this.handleSubmit, hasAuth: true },
      ]
      return btns.filter(item => !item.hasAuth || (item.hasAuth && this.showBtn(item.btnTxet)));
    },
    handleClearForm () {
      this.formData = {
        processingStatusList: ['0', '1', '3', '4'], // 处理状态
        categoryUuids: null, // 是否物流中心
        isLogistic: null, // 是否物流中心
        companyId: null, // 分公司
        areaId: null, // 区域
        centerId: null, // 归属中心
        stockAttr: null, // 存量溢出属性
        processingUserName: '', // 处理人
        brandUuid: null, // 品牌
        departmentId: null, // 归属部门
        productName: '', // 商品名称
        skuNo: '', // 商品编码
        processingType: null, // 处理方式
        planDigestionRegion: null, // 预计消化区间
        isSolveDateModify: null, // 预计解决日期是否变化
        statisticsDate: [], // 统计日期
        planSolveUpdateDate: [], // 预计解决日期
        enumTempProduct: '', // 商品类型
        stockId: null, // 仓位
        supplyName: '', // 供应商
        isSeason: null, // 是否季节性商品
        qualityGuaranteePeriodType: null, // 保质期类型
        productStockAttribute: null, // 存量属性
        isSolutionReasonable: null, // 是否合理
        stockDate: [], // 新做库存日期
        unStockDate: [], // 不做库存日期
        isPushManage: '', // 不做库存日期
        processDepartmentId: '', // 处理部门
      }
    },
    // 初始化查询条件
    initSearchParams () {
      const [dataDateBegin = '', dataDateEnd = ''] = this.formData.statisticsDate || [];
      const [planSolveDateBegin = '', planSolveDateEnd = ''] = this.formData.planSolveUpdateDate || [];
      const [stockDateBegin = '', stockDateEnd = ''] = this.formData.stockDate || [];
      const [unStockDateBegin = '', unStockDateEnd = ''] = this.formData.unStockDate || [];
      return {
        dataDateBegin,
        dataDateEnd,
        planSolveDateBegin,
        planSolveDateEnd,
        stockDateBegin,
        stockDateEnd,
        unStockDateBegin,
        unStockDateEnd,
        ..._.omit(this.formData, 'statisticsDate', 'planSolveUpdateDate', 'stockDate', 'unStockDate')
      }
    },
    // 获取表格数据 by 查询表单
    async getTableDataAction () {
      setAuthBtnId()
      this.tableInfo.list = [];
      const params = {
        ...this.pagination,
        ...this.initSearchParams()
      }
      const res = await queryStockListService(params, state => { this.tableInfo.loading = state })
      if (res) {
        const { results, totalNum } = res.retData;
        this.tableInfo.list = results;
        this.pagination.totalNum = totalNum;
        let totalAmount = 0;
        totalAmount = results.reduce((totalAmount, item) => (totalAmount += item.stockPrice), 0)
        this.totalAmount = toFixedCustomize(totalAmount);
      }
    },
    // 获取查询条件下拉集合
    async getSearchConditionOptionsAction () {
      setAuthBtnId()
      const res = await querySearchConditionOptionsService({}, state => { this.searchFormLoading = state })
      if (res) {
        this.searchOptionObj = res.retData;
        this.formItemList = initFormItemList(res.retData);
      } else {
        this.formItemList = initFormItemList(this.searchOptionObj);
      }
      this.showSearchForm = true;
    },
    // 导出
    async handleExportFile () {
      if (this.pagination.totalNum > 300000) {
        return this.$message.warning('导出数据量不能超过30万')
      }
      setAuthBtnId()
      const res = await exportStockFileService(this.initSearchParams(), state => { this.exportLoading = state })
      if (res) {
        createExcelByExport({ res, excelTitle: '存量溢出' });
      }
    },
    // 显示处理日志
    async handleShowLog (row) {
      const res = await dealLogService({ id: row.id }, state => { this.tableInfo.loading = state })
      if (res && res.retData) {
        this.dealLogList = res.retData;
        this.logDialogVisible = true;
      }
    },
    // 勾选需要处理的库存
    selectionChange (rows) {
      this.tableInfo.selection = rows;
    },
    // 获取表单内容
    getFormData (data) {
      this.formData = data;
    },
    // 表单查询
    handleQueryForm () {
      this.pagination.nowPage = 1;
      this.getTableDataAction();
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableDataAction();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableDataAction();
    },
    // 处理存量
    handleDealConfirm (data) {
      this.getTableDataAction();
    },
    // 处理存量
    handleDealStock () {
      if (this.tableInfo.selection.length === 0) {
        return this.$message.warning('请勾选需要处理的项');
      }
      validProcessAuthService(this.selectIds).then((res) => {
        if (res && res.retData == 1) {
          setAuthBtnId('处理')
          this.dealDialogVisible = true;
        } else {
          this.$message.warning('无操作权限')
        }
      })
    },
    // 关闭处理弹框
    handleCloseDialog () {
      this.dealDialogVisible = false;
      this.logDialogVisible = false;
    },
    // 跨区域转货
    handleCrossRegionalTransfer () {
      this.transferVisible = true;
    },
    // 转货 optType:  1，转集团；2 转区域；3  跨区域转派
    async handleTransfer (optType, areaId) {
      const params = {
        optType,
        idList: this.selectIds,
        areaId: areaId || ''
      }
      const res = await transferGoodsService(params, state => { this.transferLoading = state })
      if (res) {
        this.$message.success('操作成功')
        this.getTableDataAction()
      }
    },
    // 打开弹窗
    handleOpenDialog (visible) {
      if (visible == 'reviewVisible') {
        const { selection } = this.tableInfo;
        if (selection.some(item => item.processingStatus != 1)) {
          return this.$message.warning('只有处理中状态可进行复核');
        }
      }
      if (visible == 'exportVisible') {
        setAuthBtnId('导入')
      }
      this[visible] = true;
    },
    // 重置处理部门
    async handleResetDepartment () {
      const ids = this.tableInfo.selection.map(item => item.id)
      const res = await resetProcessDeptService(ids, state => { this.resetLoading = state })
      if (res) {
        this.$message.success('操作成功')
        this.getTableDataAction()
      }
    },
    // 提交
    handleSubmit () {
      // 待提交状态 processingStatusStr
      const { selection } = this.tableInfo;
      if (selection.some(item => item.processingStatus != 3)) {
        return this.$message.warning('只有待提交状态的才能进行操作');
      }
      if (selection.some(item => item.processingType != selection[0].processingType)) {
        return this.$message.warning('请选择相同处理方式的数据进行提交');
      }
      // 14 留存销售 5 打折退厂 3 内部促销
      if ([3, 5, 14].includes(selection[0].processingType)) {
        return this.$confirm(`您选择的处理方式是${selection[0].processingTypeStr},数据提交后需要审核`, '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '提交',
        })
          .then(() => {
            this.submitStockAction()
          })
          .catch(() => {});
      }
      // 处理方式为“报废”进入【报废申请单】详情页
      if (selection[0].processingType == 18) {
        this.$router.push({ name: 'addScrapApplication', params: { idList: this.selectIds } })
      }
      // 处理方式为“跨区域转货”进入【跨区域转货】详情页
      if (selection[0].processingType == 7) {
        this.$router.push({ name: 'addTransferGoods', params: { idList: this.selectIds } })
      }
    },
    async submitStockAction () {
      setAuthBtnId('提交')
      const res = await submitStockService(this.selectIds, state => { this.submitLoading = state })
      if (res) {
        this.$message.success('提交成功');
        this.getTableDataAction();
      }
    },
    handleShowSpplier (row) {
      this.itemId = row.id;
      this.spplierVisible = true;
    }
  }
};
</script>
